from db import db


class ACL(object):
    def __init__(self):
        pass

    # 添加权限
    def set_resource(self, uid, reslist):
        for i in reslist:
            sql = "insert into user_resource(userid,resourceid)values (%d,%d)" % (int(uid), int(i))
            db.update(sql)

    # 修改权限
    def update_resource(self, uid, reslist):
        # 先删除在添加
        sql = "delete from user_resource where userid=%d" % (int(uid))
        db.update(sql)
        self.set_resource(uid, reslist)

    # 删除某个权限
    def delete_resource(self, uid, resourceid):
        sql = "delete from user_resource where userid=%d and resourceid=%d" % (int(uid), int(resourceid))
        db.update(sql)

    # 获取页面资源列表 type=1的为前端资源
    def get_page_reslist(self, uid):
        sql = "select r.url as url from user_resource as ur inner join resource as r on ur.resourceid=r.id where ur.userid=%d and r.type=1" % (
            int(uid))
        res = db.find_all(sql)
        list = []
        for i in res:
            list.append(i['url'])
        return list

    # 获取接口资源列表   type=2的为后端资源
    def get_interface_reslist(self, uid):
        "select r.url from user_resource as ur inner join resource as r on ur.resourceid=r.id where ur.userid=%d and r.type=1" % (
            int(uid))
        res = db.find_all(sql)
        list = []
        for i in res:
            list.append(i['url'])
        return list


acl = ACL()
